package com.example.day02.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.bumptech.glide.Glide;
import com.example.day02.R;
import com.example.day02.bean.BelleBean;

import java.util.ArrayList;
import java.util.List;

public class RlvAdapter extends RecyclerView.Adapter<RlvAdapter.ViewHolder> {

    private Context context;
    public List<BelleBean.ResultsBean> datas = new ArrayList<>();
    private OnItemClickListener onItemClickListener;

    public RlvAdapter(Context context) {
        this.context = context;
    }

    public void setDatas(List<BelleBean.ResultsBean> datas) {
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RlvAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RlvAdapter.ViewHolder viewHolder, final int i) {
        BelleBean.ResultsBean resultsBean = datas.get(i);

        viewHolder.tv_item.setText(resultsBean.getDesc());
        Glide.with(context).load(resultsBean.getUrl()).into(viewHolder.iv_item);

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null){
                    onItemClickListener.onItemClick(v,i);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_item;
        TextView tv_item;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_item = itemView.findViewById(R.id.iv_item);
            tv_item = itemView.findViewById(R.id.tv_item);
        }
    }


    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }
}
